//index.js
//获取应用实例
const app = getApp();
let _this = "";
/**
   * 公共生成方法
   */
 const PublicAddTo = {
  _image: function(obj) {
    return (
      {
        active: obj.active ? obj.active : false,
        id: `drag-${obj.index}`,
        type: 'image',
        url: obj.url,
        css: {
          top: obj.top ? obj.top : '',
          left: obj.left ? obj.left :'',
          width: obj.width ? obj.width : '',
          height: obj.height ? obj.height : '',
          rotate: obj.rotate ? obj.rotate : '',
          minWidth: '60rpx',
          borderRadius: `${obj.borderRadius}`,
          x: 0,
          y: 0,
          scale: 1,
          angle: 0,
          active: false,
          new_rotate: 0,
          rotate: 0,
        },
      }
    );
  },
  _text: function (obj) {
    return(
      {
        id: `drag-${obj.index}`,
        active: false,
        type: 'text',
        text: obj.text,
        showActive: false,
        css: {
          rotate: obj.rotate,
          top: obj.top ? obj.top : 50,
          left: obj.left ? obj.left : 50,
          fontSize: obj.fontSize ? obj.fontSize : 28,
          color: obj.color ? obj.color : "#000",
          maxLines: obj.maxLines,
          lineHeight: obj.lineHeight,
          fontWeight: obj.fontWeight,
          textDecoration: obj.textDecoration, //文本修饰，支持 underline、 overline、 line-through，也可组合使用
          //字体，如需加载网络字体，前提前使用 wx.loadFontFace 进行加载（https://developers.weixin.qq.com/miniprogram/dev/api/media/font/wx.loadFontFace.html）
          fontFamily: obj.fontFamily ? obj.fontFamily : "微软雅黑",
          fontName: obj.fontName ? obj.fontName : "微软雅黑",
          background: obj.background,
          padding: obj.padding,
          textAlign: obj.textAlign,
          shape: "",
          x: 155,
          y: 155,
          scale: 1,
          angle: 0,
          new_rotate: 0,
          rotate: 0,
          width: 0,
          height: 0,
        },
      }
    )
  },
 }
 let items = [
  { 
    id:"text0",
    type:"text",
    text:"请输入文字",
    showActive: false,
    css: {
      top: 50,
      left: 50,
      shape: "",
      x: 155,
      y: 155,
      color: "#000",
      fontFamily: "微软雅黑",
      fontName: "微软雅黑",
      fontSize: 28,
      scale: 1,
      angle: 0,
      active: false,
      new_rotate: 0,
      rotate: 0,
      width: 150,
      height: 0,
    },
 }];
 let index = 0;
 var windowWidth = 750;

//  字体
const FontFamily = [
  {
    name: '宋体',
    fontFamily: 'SimSun',
  },
  {
    name: '黑体',
    fontFamily: 'SimHei',
  },
  {
    name: "微软雅黑",
    fontFamily: "Microsoft Yahei",
  },
  {
    name: "微软正黑体",
    fontFamily: "Microsoft JhengHei",
  },
  {
    name: "楷体",
    fontFamily: "KaiTi",
  },
  {
    name: "新宋体",
    fontFamily: "NSimSun",
  },
  {
    name: "仿宋",
    fontFamily: "FangSong",
  },
];
// 存储当前获取的字体
let CurrentFont = "";
// 颜色列表
const colorList = [
  "#000000",
  "#cccccc",
  "#ffffff",
  "#3e2622",
  "#795547",
  "#d7ccca",
  "#b71d1d",
  "#dc100f",
  "#ee9a9a",
  "#e65100",
  "#f67c01",
  "#fbbe2f",
  "#877a2b",
];

Page({
  data: {

    width: 50,//宽度
    height: 300,//高度
    max_width: 400,
    max_height: 400,
    disable_rotate:true,//是否禁用旋转
    disable_ratio: false,//锁定比例
    limit_move: true,//是否限制移动
    
    // 添加文字弹框状态
    addTextAlert: false,
    // 获取焦点
    onFocus: false,
    //文字
    textVal: "请输入文字",
    // 所有
    allList: [],
    // 字体大小
    fontSize: 16,
    // 字体颜色
    color: "",
    // 字体名字
    fontName: "",
    // 设置字体滑块显示
    blockSizeShow: false,

    // 步骤 : 1:首页, 2:点击添加后显示的, 3:点击文字显示文字修改栏目
    step: 1,
    // 是否是修改状态
    modifyState: false,
    // 是否显示选择字体板块
    FontFamilyState: false,
    // 显示颜色
    colorState: false,
    // 是否显示
    uploadImgShow: false,
    
  },
  /**
   * 获取保存到相册
   */
  SaveXiangCe(cb) {
    // 授权保存到相册
   wx.getSetting({
   success(res) {
     console.log(res);
     if (res.authSetting['scope.writePhotosAlbum']) {
       return cb();
     } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
       wx.authorize({
         scope: 'scope.writePhotosAlbum',
         success() {
           return cb();
         },
         fail(){
           // wx.showToast({
           //     title: '您没有授权，无法保存到相册',
           //     icon: 'none'
           // })
           console.log("您没有授权，无法保存到相册")
         }
       })
     } else {
       wx.openSetting({
         success(res) {
           if (res.authSetting['scope.writePhotosAlbum']) {
             return cb();
           }else{
             wx.showModal({
               title: '温馨提示',
               content: '请开启保存到相册的权限，开启后会自动保存到相册',
               success (res) {
                 if (res.confirm) {
                   wx.openSetting({
                     success(res) {
                       if (res.authSetting['scope.writePhotosAlbum']) {
                         return cb();
                       }
                     }
                   })
                 } else if (res.cancel) {
                   console.log('用户点击取消')
                 }
               }
             })
           }
         }
       })
     }
   }
 }); 
},
/**
 * 画图片
 */
paintingImg(obj) {
  return({
    type: 'image',
    url: obj.url,
    css: {
      width: obj.width * 2 + 'rpx',
      height: obj.height * 2 + 'rpx',
      mode: obj.mode ? obj.mode : 'scaleToFill',
      top: obj.top * 2 + 'rpx',
      left: obj.left * 2 + 'rpx',
      rotate: obj.rotate,
    },
  })
},
/**
 * 画文字
 */
paintingText(obj) {
  return({
    type: 'text',
    text: obj.text,
    css: {
      width: obj.width * 2 + 'rpx',
      height: obj.height * 2 + 'rpx',
      top: `${obj.top * 2}rpx`,
      left: `${obj.left * 2}rpx`,
      fontFamily: `${obj.fontFamily}`,
      color: `${obj.color}`,
      fontSize: `${obj.fontSize * 2}rpx`,
      rotate: obj.rotate,
    },
  })
},
  /**
   * 生成图片
   */
    // 点击显示
  clickAlert() {
    if (_this.data.sharePath) {
      this.setData({
        alertShow: true,
      })
      return false;
    }
    let array = [];
    console.log(items);
    // return false;

    items.map((item, index)=> {
      if(item.type == 'text') {
        array.push(_this.paintingText({
          text: item.text,
          top: item.css.top,
          left: item.css.left,
          width: item.css.width,
          fontSize: item.css.fontSize,
          fontFamily: item.css.fontFamily,
          color: item.css.color,
          rotate: item.css.rotate,
        }))
      } else {
        array.push(_this.paintingImg({
          url: item.url,
          top: item.css.top,
          left: item.css.left,
          width: item.css.width,
          height: item.css.height,
          rotate: item.css.rotate,
        }))
      }
    })



    this.SaveXiangCe(()=> {
      shengchengImg();
    });
    
    


    
    // 当前文章生成二维码
    function shengchengImg() {
      wx.showLoading({
        title: '正在生成海报',
      })

      console.log(array);
      _this.setData({
        // imgUrl: res.data,
        imgDraw: {
          width: '590rpx',
          height: '800rpx',
          background:'#ccc',
          views: array,
        },
      })
    }
  },
  /**
   * 生成图片完成
   */
  onImgOK(e) {
    wx.hideLoading()
    wx.saveImageToPhotosAlbum({
      filePath: e.detail.path,
      success(res) {
        console.log(res);
      }
    })
    // this.previewImg2();
    //通知外部绘制完成，重置isCanDraw为false
    this.triggerEvent('initData')
  },
  /**
   * 选择颜色
   */
  changeColor(e) {
    const color = e.currentTarget.dataset.color;
    items[index].css.color = color;
    this.setData({
      allList: items,
      color: color,
    })
  },
  /**
   * 显示色板
   */
  showColorTab() {
    this.setData({
      colorState: true,
    })
  },
  /**
   * 取消
   */
  hideColorTab() {
    this.setData({
      colorState: false,
    })
  },
  /**
   * 修改文字
   */
  changeText() {
    this.setData({
      modifyState: true,
      addTextAlert: true,
      textVal: items[index].text,
    })
  },
  /**
   * 显示所有可以修改的文字
   */
  showTextAll() {
    items.map((item, index)=> {
      if (item.type == 'text') {
        item.showActive = true;
      }
    })
    this.setData({
      allList: items
    })
  },
  /**
   * 显示选择字体弹窗
   */
  showFamilyBox() {
    this.setData({
      FontFamilyState: true,
    })
  },
  /**
   * 选择字体
   */
  changeFamily(e) {
    items[index].css.fontFamily = e.currentTarget.dataset.fontfamily;
    items[index].css.fontName = e.currentTarget.dataset.fontname;
    CurrentFont = items[index].css.fontFamily;
    this.setData({
      allList: items,
      fontName: e.currentTarget.dataset.fontname,
    })
  },
  /**
   * 取消字体选
   */
  cancelText(e) {
    items[index].css.fontFamily = CurrentFont;
    this.setData({
      allList: items,
      FontFamilyState: false,
    })
  },
  /**
   * 确认字体
   */
  yesText(e) {
    this.setData({
      FontFamilyState: false,
    })
  },
  /**
   * 修改步骤状态
   */
  changeStep(e) {
    this.setData({
      step: e.currentTarget.dataset.step,
    })
  },
  /**
   * 显示修改字体大小弹框
   */
  showBlock() {
    this.setData({
      blockSizeShow: true,
    })
  },
  //获取数据移动前的角度
  countDeg(cx, cy, pointer_x, pointer_y) {
    var ox = pointer_x - cx;
    var oy = pointer_y - cy;
    var to = Math.abs(ox / oy);
    var angle = Math.atan(to) / (2 * Math.PI) * 360; //鼠标相对于旋转中心的角度
    if (ox < 0 && oy < 0) //相对在左上角，第四象限，js中坐标系是从左上角开始的，这里的象限是正常坐标系  
    {
      angle = -angle;
    } else if (ox <= 0 && oy >= 0) //左下角,3象限  
    {
      angle = -(180 - angle)
    } else if (ox > 0 && oy < 0) //右上角，1象限  
    {
      angle = angle;
    } else if (ox > 0 && oy > 0) //右下角，2象限  
    {
      angle = 180 - angle;
    }
    return angle;
  },
  /**
   * 删除
   */
  delItem(e) {
    const id = e.currentTarget.dataset.id;
    items.map((item, index)=> {
      if (item.id == id) {
        items.splice(index,1);
      }
    })
    this.setData({
      allList: items,
    })
  },
  /**
   * 移动组件函数 start
   */
  onMove(e) {
    //移动时的坐标值也写图片的属性里
    items[index].css._lx = e.touches[0].clientX;
    items[index].css._ly = e.touches[0].clientY;

    //追加改动值
    items[index].css.left += items[index].css._lx - items[index].css.lx; // x方向
    items[index].css.top += items[index].css._ly - items[index].css.ly; // y方向
    items[index].css.x += items[index].css._lx - items[index].css.lx;
    items[index].css.y += items[index].css._ly - items[index].css.ly;

    //把新的值赋给老的值
    items[index].css.lx = e.touches[0].clientX;
    items[index].css.ly = e.touches[0].clientY;
    this.setData({ //赋值就移动了
      allList: items
    })
  },
  moveStart(e) {
    var self = this;
    let color= "",
        fontSize = "",
        fontName = "";
    for (let i = 0; i < items.length; i++) { //旋转数据找到点击的
      items[i].active = false;
      items[i].showActive = false;
      if (e.currentTarget.dataset.id == items[i].id) {
        index = i; //记录下标
        items[index].active = true; //开启点击属性
        if (items[index].type == 'text') {
          items[i].showActive = true;
          fontSize = items[index].css.fontSize;
          fontName = items[index].css.fontName;
          color = items[index].css.color;
        }
      }
    }

    items[index].css.lx = e.touches[0].clientX; // 记录点击时的坐标值
    items[index].css.ly = e.touches[0].clientY;

    var query = wx.createSelectorQuery()

    if (items[index].css.width == 0) {
      query.select('#drag-' + items[index].id).fields({
        dataset: true,
        size: true,
        scrollOffset: true,
        rect: true,
        properties: ['scrollX', 'scrollY'],
        computedStyle: ['fontSize', 'color', 'transform']
      }, function(res) {
        console.log(res);
        items[index].css.width = 250
        items[index].css.height = 50
      }).exec(function(res) {});
    }
    this.setData({ //赋值 
      allList: items,
      hasActive: true,
      step: items[index].type == 'text' ? 3 : 1,
      color: color,
      fontSize: fontSize,
      fontName: fontName,
    })
  },
  // 添加图片
  addImg() {
    let that = this;
    that.setData({
      uploadImgShow: true,
    });
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '加载中',
        })
        const tempFilePaths = res.tempFilePaths[0];
        wx.getImageInfo({
          src: tempFilePaths,
          success (res) {
            wx.navigateTo({
              url: '/pages/cropper/cropper?src=' + tempFilePaths + '&width=' + res.width + '&height=' + res.height,
            })
          }
        })
      }
    })
  },
  /**
   * 裁剪后图片渲染
   */
  changeItems: function(obj){
    
    items.push(PublicAddTo._image({
      url: obj.url,
      top: 50,
      left: 50,
      width: obj.width / 4,
      height: obj.height / 4,
      active: true,
      index: items.length + 1,
    }));
    this.setData({
      allList: items,
    })
  },
  //计算触摸点到圆心的距离
  getDistancs(cx, cy, pointer_x, pointer_y) {
    var ox = pointer_x - cx;
    var oy = pointer_y - cy;
    return Math.sqrt(
      ox * ox + oy * oy
    );
  },
  /**
   * 输入框输入事件
   */
  changeVal(e) {
    const textVal = e.detail.value;
    this.setData({
      textVal,
    })
  },
  /**
   * 添加文字
   */
  addText() {
    this.setData({
      addTextAlert: true,
      onFocus: true,
    })
  },
  /**
   * 确认添加文字
   */
  addTextTap() {
    const textVal = this.data.textVal;
    const modifyState = this.data.modifyState;
    if (!modifyState) {
      items.push(PublicAddTo._text({
        text: textVal,
        index: items.length + 1,
      }));
    } else {
      items[index].text = textVal;
    }
    
    this.setData({
      allList:items,
      addTextAlert: false,
      modifyState: false,
    })
  },
  /**
   * 取消文字输入框显示
   */
  cnaelTap() {
    this.setData({
      addTextAlert: false,
      onFocus: false,
    })
  },
  // 触摸开始事件  items是this.data.itemList的全局变量，便于赋值  所有的值都应给到对应的对象里
  touchStart: function(e) {
    console.log(e);
    //找到点击的那个图片对象，并记录
    for (let i = 0; i < items.length; i++) {
      items[i].active = false;
      if (e.currentTarget.dataset.id == items[i].id) {
        index = i;
        items[index].active = true;
      }
    }
    //获取作为移动前角度的坐标
    items[index].css.tx = e.touches[0].clientX;
    items[index].css.ty = e.touches[0].clientY;
    //移动前的角度
    items[index].css.anglePre = this.countDeg(items[index].css.x, items[index].css.y, items[index].css.tx, items[index].css.ty)
    //获取图片半径
    items[index].css.r = this.getDistancs(items[index].css.x, items[index].css.y, items[index].css.left, items[index].css.top)
  },
  // 触摸移动事件  
  touchMove: function(e) {
    //记录移动后的位置
    items[index].css._tx = e.touches[0].clientX;
    items[index].css._ty = e.touches[0].clientY;
    //移动的点到圆心的距离  * 因为圆心的坐标是相对与父元素定位的 ，所有要减去父元素的OffsetLeft和OffsetTop来计算移动的点到圆心的距离
    items[index].css.disPtoO = this.getDistancs(items[index].css.x, items[index].css.y, items[index].css._tx - windowWidth * 0.125, items[index].css._ty - 10)

    // //计算移动后的宽高
    items[index].css.width += (items[index].css._tx - items[index].css.tx);
    items[index].css.height += (items[index].css._ty - items[index].css.ty);
    if (items[index].shape == "round") {
      if ((items[index].css._tx - items[index].css.tx) > 0) {
        items[index].css.width = items[index].css.height;
      } else {
        items[index].css.width = items[index].css.height;
      }
    }


    //用过移动后的坐标赋值为移动前坐标
    items[index].css.tx = e.touches[0].clientX;
    items[index].css.ty = e.touches[0].clientY;
    items[index].css.anglePre = this.countDeg(items[index].css.x, items[index].css.y, items[index].css.tx, items[index].css.ty)

    //赋值setData渲染
    this.setData({
      allList: items
    })
  },
  blur() {
    var self = this;
    for (let i = 0; i < items.length; i++) { //旋转数据找到点击的
      items[i].active = false;
      items[i].showActive = false;
    }
    this.setData({
      allList: items,
      hasActive: false,
      step: 1,
      colorState: false,
      FontFamilyState: false,
      blockSizeShow: false,
    })
  },
  touchRotate: function(e) {

    if (this.pubRotate >= 3) {
      this.pubRotate = 0;
    } else {
      ++this.pubRotate;
      return;
    }
    items[index].active = true;
    // //记录移动后的位置
    items[index].css._tx = e.touches[0].clientX;
    items[index].css._ty = e.touches[0].clientY;
    //移动的点到圆心的距离  * 因为圆心的坐标是相对与父元素定位的 ，所有要减去父元素的OffsetLeft和OffsetTop来计算移动的点到圆心的距离
    items[index].css.disPtoO = this.getDistancs(items[index].css.x, items[index].css.y, items[index].css._tx - windowWidth * 0.125, items[index].css._ty - 10)
    // items[index].scale = items[index].disPtoO / items[index].r; //手指滑动的点到圆心的距离与半径的比值作为图片的放大比例
    // items[index].oScale = 1 / items[index].scale; //图片放大响应的右下角按钮同比缩小

    //移动后位置的角度
    items[index].css.angleNext = this.countDeg(items[index].css.x, items[index].css.y, items[index].css._tx, items[index].css._ty)
    //角度差
    items[index].css.new_rotate = items[index].css.angleNext - items[index].css.anglePre;

    //叠加的角度差
    items[index].css.rotate += items[index].css.new_rotate;
    items[index].css.angle = items[index].css.rotate; //赋值


    //用过移动后的坐标赋值为移动前坐标
    items[index].css.tx = e.touches[0].clientX;
    items[index].css.ty = e.touches[0].clientY;
    items[index].css.anglePre = this.countDeg(items[index].css.x, items[index].css.y, items[index].css.tx, items[index].css.ty)
    console.log(items);
    //赋值setData渲染
    this.setData({
      allList: items
    })
  },
  /**
   * 字体大小拖动事件
   */
  slider1change(e) {
    items[index].css.fontSize = e.detail.value;
    console.log(items);
    this.setData({
      fontSize: e.detail.value,
      allList: items,
    })
  },
  /**
   * 字体确认
   */
  determineSize(e) {
    this.setData({
      blockSizeShow: false,
    })
  },
  /**
   * 页面加载
   */
  onLoad: function() {
    this.setData({
      allList: items,
      FontFamily,
      colorList,
    })
    this.pubRotate = 0;
    _this = this;
  },

})
